<template>
  <div class="login">
    <div class="login-box">
      <h3 class="login-title">健身房管理系统</h3>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item prop="tel">
          <el-input v-model="ruleForm.tel" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item prop="pwd">
          <el-input v-model="ruleForm.pwd" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="checked">记住我</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 100%;" type="primary" @click="submitForm('ruleForm')">立即登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { managerLogin } from '@/api/login'
import md5 from 'crypto-md5'
export default {
  name: 'Login',
  data () {
    return {
      checked: false,
      ruleForm: {
        tel: null,
        pwd: null
      },
      rules: {
        tel: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    if (localStorage.getItem('checked')) {
      this.checked = true
      this.ruleForm.tel = localStorage.getItem('tel')
      this.ruleForm.pwd = localStorage.getItem('pwd')
    }
  },
  methods: {
    submitForm (formName) {
      // 表单的验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 判断是否记住密码
          if (this.checked) {
            localStorage.setItem('tel', this.ruleForm.tel)
            localStorage.setItem('pwd', this.ruleForm.pwd)
            localStorage.setItem('checked', this.checked)
          } else {
            localStorage.removeItem('tel')
            localStorage.removeItem('pwd')
            localStorage.removeItem('checked')
          }
          // 验证成功
          const pwd = md5(this.ruleForm.pwd, 'hex')
          managerLogin({...this.ruleForm, pwd }).then(res => {
            const { token, userId } = res
            localStorage.setItem('token', token)
            localStorage.setItem('userId', userId)
            this.$router.push('/')
          }).catch(err => {
            console.log(err);
          })
        } else {
          // 验证失败
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
.login {
  height: 100%;
  background: url('../assets/image/bg.jpg') no-repeat;
  background-size: cover;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.login-box {
  width: 330px;
  background-color: white;
  border-radius: 10px;
  padding: 40px 40px 20px 40px;
}
.login-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
</style>
